/* INCLUDES ******************************************************************/

#include "ses_button.h"
#include "ses_dcf77.h"
#include "ses_scheduler.h"

#define BUTTON_ROTARY_PORT		PORTB
#define BUTTON_ROTARY_PIN		6
#define BUTTON_JOYSTICK_PORT	PORTB
#define BUTTON_JOYSTICK_PIN		7

/* PRIVATE VARIABLES *********************************************************/

pButtonCallback _rotary_callback;
pButtonCallback _joystick_callback;

/* FUNCTION DEFINITION *******************************************************/

void button_init() {
	/* Set Pins to Input */
	DDR(BUTTON_ROTARY_PORT) &= ~(1 << BUTTON_ROTARY_PIN);
	DDR(BUTTON_JOYSTICK_PORT) &= ~(1 << BUTTON_JOYSTICK_PIN);
	DDR(DCF77_PORT) &= ~(1 << DCF77_PIN);

	/* Enable Pullup */
	BUTTON_ROTARY_PORT |= (1 << BUTTON_ROTARY_PIN);
	BUTTON_JOYSTICK_PORT |= (1 << BUTTON_JOYSTICK_PIN);

	/* Enable Interrupts */
	PCICR = (1 << PCIE0);
	PCMSK0 = (1 << PCINT7) | (1 << PCINT6) | (1 << PCINT4);
}

void button_setRotaryButtonCallback(pButtonCallback callback) {
	_rotary_callback = callback;
}

void button_setJoystickButtonCallback(pButtonCallback callback) {
	_joystick_callback = callback;
}

// interrupt service routine for pin change interrupt 7:0
ISR(PCINT0_vect)
{
	//Check if Rotary Button is pressed
	if (button_isJoystickPressed() && _rotary_callback != NULL) {
		scheduler_add(_rotary_callback, 0);
		return;
	}

	//Check if Rotary Button is pressed
	if (button_isRotaryPressed() && _joystick_callback != NULL) {
		scheduler_add(_joystick_callback, 0);
		return;
	}

	//Else DCF77 pin toggle
	dcf77_PinToggle();
}

uint8_t button_isRotaryPressed(){
	return !(PIN(BUTTON_JOYSTICK_PORT) & (1 << BUTTON_JOYSTICK_PIN));
}

uint8_t button_isJoystickPressed(){
	return !(PIN(BUTTON_ROTARY_PORT) & (1 << BUTTON_ROTARY_PIN));
}
